package application

import (
	"context"
	"fmt"

	"im-demo/application/conf"

	"github.com/go-redis/redis"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	MysqlClient   *gorm.DB
	RedisClient   *redis.Client
	MongoDBClient *mongo.Client

	MongoDataBaseName            = "im-demo"
	MongoMsgCollection           = "message"
	MongoSessionListCollection   = "session_list"
	MongoFriendRequestCollection = "friend_request"
)

func init() {
	// MysqlClient = intiMysql()
	RedisClient = initRedis()
	MongoDBClient = initMongoDB()
}

func intiMysql() *gorm.DB {
	fmt.Println("mysql is connecting...")

	uri := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", conf.MysqlConf.Username, conf.MysqlConf.Password, conf.MysqlConf.Host, conf.MysqlConf.Port, conf.MysqlConf.Database)
	db, err := gorm.Open("mysql", uri)

	if err != nil {
		panic(err)
	} else {
		fmt.Println("mysql connectiton success")
	}
	// 设置全局表名禁用复数
	db.SingularTable(true)

	return db
}

func initRedis() *redis.Client {
	fmt.Println("redis is connecting...")

	client := redis.NewClient(&redis.Options{
		Addr:     conf.RedisConf.Host + ":" + conf.RedisConf.Port, // "127.0.0.1:6379"
		Password: conf.RedisConf.Password,                         // ""
		DB:       conf.RedisConf.Db,                               // 0
	})

	err := client.Ping().Err()
	if err != nil {
		panic(err)
	} else {
		fmt.Println("redis connectiton success")
	}

	return client
}

func initMongoDB() *mongo.Client {
	fmt.Println("mongodb is connecting...")

	uri := fmt.Sprintf("mongodb://%s:%s@%s:%d/%s", conf.MongoDbConf.Username, conf.MongoDbConf.Password, conf.MongoDbConf.Host, conf.MongoDbConf.Port, conf.MongoDbConf.Db)
	clientOptions := options.Client().ApplyURI(uri)

	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		panic(err)
	}

	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		panic(err)
	}
	println("mongodb connectiton success")

	return client
}
